package com.wc.community.controller;

import com.wc.community.dto.AccessTokenDTO;
import com.wc.community.dto.GitUser;
import com.wc.community.mapper.UserMapper;
import com.wc.community.model.User;
import com.wc.community.provider.GitProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.data.ConditionalOnRepositoryType;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * @author wc
 * @create 2021-06-16-18:01
 * @desc
 */
@Controller
public class AuthorizeController {
    @Autowired
    private GitProvider gitProvider;

    @Value("${git.client.id}")
    private String clientId;

    @Value("${git.client.secret}")
    private String clientSecret;

    @Value("${git.redirect.uri}")
    private String redirectUrl;

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/callback")
    public String callback(@RequestParam(name="code")String code,
                           @RequestParam(name="state")String state,
                           HttpServletRequest request) throws NoSuchAlgorithmException, KeyManagementException {
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
        accessTokenDTO.setCode(code);
        accessTokenDTO.setRedirectUri(redirectUrl);
        accessTokenDTO.setState(state);
        accessTokenDTO.setClientId(clientId);
        accessTokenDTO.setClientSecret(clientSecret);
        String accessToken = gitProvider.getAccessToken(accessTokenDTO);
        GitUser gituser = gitProvider.getUser(accessToken);
        if(gituser!=null){
            User user = new User();
            user.setToken(UUID.randomUUID().toString());
            user.setUserName(gituser.getName());
            user.setAccountId(String.valueOf(gituser.getId()));
            user.setGmtCreate(System.currentTimeMillis());
            user.setGmtModified(user.getGmtCreate());
            userMapper.insert(user);
            //登录成功写的Session
            request.getSession().setAttribute("user",gituser);
        }else {
            //
            request.getSession().setAttribute("user",null);
        }
        return "redirect:/";
    }
}
